<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org  ">
<head>
  <meta charset="UTF-8">
  <title>登录</title>
  <!-- Crypto-JS 提供 MD5 -->
  <script src="https://cdn.bootcdn.net/ajax/libs/crypto-js/4.1.1/crypto-js.min.js  "></script>
</head>
<body>
<h2>用户登录</h2>

<!-- 登录表单 -->
<form id="loginForm" method="post" th:action="@{/login/dologin}">
  用户名：<input type="text" name="username" required/><br/>
  密　码：<input type="password" id="password" required/><br/>
  <!-- 把 salt 和加密后的密码隐藏提交 -->
  <input type="hidden" name="salt" id="salt"/>
  <input type="hidden" name="passwordHash" id="passwordHash"/>
  <button type="submit">登录</button>
</form>

<script>
  // 拦截表单提交，先在前端做 salt + MD5
  document.getElementById('loginForm').addEventListener('submit', function (e) {
    e.preventDefault();                       // 阻止原生提交

    const pwd = document.getElementById('password').value;

    const salt ="1a2b3c4d";
    const strpwd=salt.charAt(0)+salt.charAt(1)+pwd+salt.charAt(3)+salt.charAt(4);

    const hash = CryptoJS.MD5(strpwd).toString(); // MD5(密码+盐)

    // 把 salt 和 hash 塞进隐藏域
    document.getElementById('salt').value = salt;
    document.getElementById('passwordHash').value = hash;

    // 使用 fetch 进行异步提交
    fetch(this.action, {
      method: 'POST',
      body: new FormData(this)
    })
            .then(response => response.json())
            .then(result => {
              // 弹窗显示 msg
              alert(result.msg);
              // 如果 code == 200，跳转到 /login/tolist
              if (result.code === 200) {
                window.location.href = '/goods/tolist';
              }
            })
            .catch(error => {
              console.error('登录请求失败:', error);
              alert('登录请求失败，请重试');
            });
  });
</script>
</body>
</html>